package com.feinno.urcs.group.fxdb;

import com.feinno.database.ConnectionString;
import com.feinno.database.Database;
import com.feinno.database.spi.DatabaseManager;
import org.helium.framework.BeanContext;
import org.helium.framework.BeanIdentity;
import org.helium.framework.configuration.ConfigProvider;
import org.helium.framework.configuration.FieldLoader;
import org.helium.framework.entitys.KeyValueNode;
import org.helium.framework.entitys.SetterNode;

import java.io.IOException;
import java.util.HashMap;

/**
 * Created by Lei Gao on 7/13/15.
 */
public class PooledDatabaseLoader implements FieldLoader {
	/**
	 *
	 * @param node
	 * @return Map<Integer, Database>
	 */
	@Override
	public Object loadField(SetterNode node) {

		BeanIdentity id = BeanIdentity.parseFrom(ConfigProvider.BEAN_ID);
		ConfigProvider configProvider = (ConfigProvider)BeanContext.getContextService().getBean(id).getBean();

		String xml = configProvider.loadText(node.getInnerText());
		PooledDatabaseConfiguration configuration = new PooledDatabaseConfiguration();
		configuration.parseXmlFrom(xml);

		HashMap<Integer, Database> dbs = new HashMap<>();
		for (KeyValueNode e: configuration.getDatabases()) {
			Integer pool = Integer.parseInt(e.getKey());
			String dbName = e.getValue();
			String connStr = configProvider.loadText(dbName + ".properties");

			Database db = null;
			try {
				db = DatabaseManager.INSTANCE.getDatabase(dbName, ConnectionString.fromText(connStr));
			} catch (IOException ex) {
				throw new IllegalArgumentException("Bad connection strings for:" + dbName, ex);
			}
			dbs.put(pool, db);
		}
		return dbs;
	}
}
